import TIM from 'tim-js-sdk'
import TIMUploadPlugin from 'tim-upload-plugin'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import moment from 'moment'
import { reactive, ref, inject, watch, onMounted } from 'vue'

export default () => {
    const api = inject('api')
    const store = useStore()

    const tim = ref(null)
    const imParams = reactive({
        id: '',
        groupID: '',
        status: ''
    })
    const message = reactive({
        disabled: true,
        loading: false,
        sendLoading: false,
        limit: 10,
        page: 1,
        list: [],
        newNum: 0,
        isShowMore: false,
        textValue: '',
    })

    // 创建文本消息
    function createTextMessage () {
        return tim.value.createTextMessage({
            to: imParams.groupID,
            conversationType: TIM.TYPES.CONV_GROUP,
            payload: {
                text: message.textValue
            }
        })
    }

    function pushNewMessage ({ msg, type = '' }) {
        // 发出去的消息不算
        let payload = msg.payload.text
        let reply = null
        message.list.push({
            userId: msg.from,
            avatar: msg.avatar,
            userName: msg.nick,
            payload,
            reply,
            time: msg.time,
            timeStr: moment(msg.time * 1000).format('YYYY-MM-DD')
        })
        message.textValue = ''

        // 收到新消息
        if (type === 'receive') {
            message.newNum ++
        }
    }

    // 发送消息
    function sendMessage () {
        if (imParams.status === 'error') {
            ElMessage.error('网络异常，请稍后重试')
            void createImUserSign(imParams.id)
            return
        }

        if (message.textValue.trim() === '') {
            ElMessage.error('请输入评论内容')
            return
        }

        message.sendLoading = true
        return new Promise((resolve) => {
            tim.value.sendMessage(createTextMessage()).then(imResponse => {
                // 发送成功
                if (imResponse.code === 0) {
                    const msg = imResponse.data.message
                    if (msg.status !== 'success') {
                        ElMessage.error('发送失败: 请稍后重试')
                        resolve(false)
                        return
                    }
                    pushNewMessage({ msg, type: 'send' })
                    setTimeout(() => resolve(true), 300)
                }
                message.sendLoading = false
            }).catch(error => {
                console.log('send error', error)
                message.sendLoading = false
                switch (Number.parseFloat(error.code)) {
                    case 10016:
                        ElMessage.error('发送失败: 内容包含敏感词，请修改后重新发送')
                        break
                    default:
                        ElMessage.error('发送失败:' + error.message)
                }
            })
        })
    }

    function eventSdkReady () {
        console.log('监听 SDK 进入 ready 状态事件触发')
        imParams.status = 'success'
        void joinGroup()
    }
    function eventNotSdkReady () {
        console.log('进入 not ready 状态时触发 ')
        imParams.status = 'error'
    }
    function eventNewMessage (res) {
        console.log('收到一条新消息 ==>', res)
        // 此为系统消息
        res.data.forEach(item => {
            if (item.from !== '@TIM#SYSTEM') {
                pushNewMessage({ msg: item, type: 'receive' })
            }
        })
    }

    // 事件监听
    function imEventListen () {
        // 监听 SDK 进入 ready 状态事件
        tim.value.on(TIM.EVENT.SDK_READY, eventSdkReady)
        //  进入 not ready 状态时触发 重新刷新此页面
        tim.value.on(TIM.EVENT.SDK_NOT_READY, eventNotSdkReady)
        // 收到推送的单聊、群聊、群提示、群系统通知的新消息
        tim.value.on(TIM.EVENT.MESSAGE_RECEIVED, eventNewMessage)
    }

    async function getImRecordPage (msgTime = '') {
        try {
            message.loading = true
            const res = await api.getImRecordPage({
                limit: message.limit,
                page: message.page,
                groupId: imParams.groupID,
                msgTime,
                fromAccountNe: 'administrator',
                recordType: 1
            })
            if (!res.code) {
                const list = message.list
                const resList = res.data.list.map(item => {
                    const content = JSON.parse(item.msgBodyJson)
                    let payload = content[0].msgContent.text
                    return {
                        type: content[0].msgType,
                        avatar: item.fromAvatar,
                        userName: item.fromNick,
                        userId: item.fromAccount,
                        payload,
                        time: item.msgTime,
                        timeStr: moment(item.msgTime * 1000).format('YYYY-MM-DD HH:mm:ss')
                    }
                })
                message.list = [...resList, ...list]
                message.isShowMore = res.data.list.length >= message.limit
            }
            message.loading = false
        } catch (err) {
            message.loading = false
            console.log(err)
        }
    }

    // 加入群组
    async function joinGroup () {
        try {
            message.loading = true
            const res = await tim.value.joinGroup({
                groupID: imParams.groupID,
                type: TIM.TYPES.GRP_AVCHATROOM
            })
            if (!res.code) {
                switch (res.data.status) {
                    // 等待管理员同意
                    case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
                        ElMessage.error('加群失败，需要等待管理员审核')
                        break
                    // 加群成功
                    case TIM.TYPES.JOIN_STATUS_SUCCESS:
                    // 已经在群中
                    case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP:
                        void getImRecordPage();
                        break
                }
            }
            message.loading = false
        } catch (err) {
            message.loading = false
            console.log(err)
        }
    }

    // im 登录
    async function imLogin (data) {
        try {
            message.loading = true
            const res = await tim.value.login({
                userID: imParams.id,
                SDKAppID: data.appid,
                userSig: data.userSign
            })
            if (!res.code) {
                if (res.data.repeatLogin) {
                    void joinGroup()
                } else {
                    imEventListen()
                }
            }
            message.loading = false
        } catch (err) {
            message.loading = false
            ElMessage.error(err)
        }
    }

    async function createImUserSign () {
        try {
            message.loading = true
            const res = await api.getImUserSign(imParams.id)
            if (!res.code) {
                tim.value = TIM.create({ SDKAppID: Number(res.data.appid) })
                tim.value.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })
                tim.value.setLogLevel(4)
                void imLogin(res.data)
            }
            message.loading = false
        } catch (err) {
            message.loading = false
            console.log(err)
        }
    }

    function clickLoadMore () {
        void getImRecordPage(message.list[0].time);
    }

    watch(() => store.state.live.im, val => {
        if (val?.imId) {
            imParams.id = val.imId
            imParams.groupID = store.state.live.detail.chatRoomNo
            if (imParams.id && imParams.groupID) {
                void createImUserSign();
                message.disabled = false
            }
        }
    })

    return {
        message,
        sendMessage,
        clickLoadMore,
    }
}
